package com.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.demo.entity.base.BaseEntity;
import com.demo.entity.base.Result;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public abstract class BaseController<T extends BaseEntity,M extends IService<T>> {
    protected M manager;

    final Logger logger = LogManager.getLogger(this.getClass().getName());

    @PostMapping("/findOne")
    public Result findOne(@RequestBody String id){
        // T t = manager.findOne(Long.valueOf(id.substring(0, id.length() - 1)));
        T t = manager.getById(Long.valueOf(id));
        return Result.success(t);
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody String id) {

        // manager.delete(Long.valueOf(id.substring(0, id.length() - 1)));
        manager.removeById(Long.valueOf(id));
        return Result.success();
    }

    @PostMapping("/deleteMessages")
    public Result deleteMessages(@RequestBody List<T> t) {
        for(int i =0;i<t.size();i++)
            manager.removeById(t.get(i).getId());
        return Result.success();
    }

    @PostMapping("/update")
    public Result update(@RequestBody T t) {
        manager.updateById(t);
        return Result.success();

    }
    @PostMapping("/save")
    public Result save(@RequestBody T t) {
        List<T> list = manager.list(null);
        for (int i =0;i<list.size();i++){
            if(t.getId()==list.get(i).getId()){
                return Result.error("已存在");
            }
        }
        Boolean istrue = manager.save(t);
        if (istrue)
            return Result.success();
        else return Result.error("保存失败");
    }
    @PostMapping("/saveFromExcel")
    public Result saveFromExcel(@RequestBody List<T> t) {
        for(int i =0;i<t.size();i++)
            manager.save(t.get(i));
        return Result.success();
    }
    @PostMapping("/findAll")
    public Result findAll() {
        List<T> list = manager.list(null);
        return Result.success(list);
    }

    @GetMapping("/findByPage")
    public Map findByPage(Integer pageNow, Integer pageSize) {
        // 参数一：当前页
        // 参数二：页面大小
        Map<String, Object> result = new HashMap<>();
        Page<T> page = new Page<>(pageNow,pageSize);
        manager.page(page);
        result.put("data", page.getRecords());
        result.put("total", manager.count());
        return result;
    }
}
